package com.douwong.student.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.douwong.student.contant.Config;
import com.douwong.student.model.ResTestProblemsInfo;
import com.douwong.student.view.MTextView;
import com.douwong.student.view.MyImageSpan;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @autor yichao
 * @time 2016/7/615:20
 * @des 过滤二进制图片数据
 */
public class ImagFilterUtil {
    private static final String TAG = ImagFilterUtil.class.getSimpleName();

    /**
     * 截取字节流图片在textview显示
     *
     * @param textView  textview控件
     * @param strSource 数据源
     */
    public static void filterImage(TextView textView, String strSource, int size) {

        strSource = ToDBC(strSource);
        //测量textview的高度
        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.EXACTLY);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.EXACTLY);
        textView.measure(w, h);
        int height = textView.getMeasuredHeight();
        if (strSource != null) {
            String regex = "<img(\\s)src=\"(.){10,100}(\\.\\w{3})\">";//截取Url图片
            String imagRegex = "<(?i)img(\\s)src(.)*?>";//获取字节数据图片
            String byteDataRegex = ",((.)*?)\">";//过滤数据字节数据
            String replaceAllUrl = strSource.replaceAll(regex, "");//截取URl图片后
            Pattern compileImage = Pattern.compile(imagRegex, Pattern.CASE_INSENSITIVE);
            Matcher matcher = compileImage.matcher(replaceAllUrl);
            SpannableString spannableString = new SpannableString(replaceAllUrl);
            while (matcher.find()) {
                String group = matcher.group();
                //在原字符串中位置
                int startIndex = replaceAllUrl.indexOf(group);
                int endIndex = group.length();
                Pattern compilebyteData = Pattern.compile(byteDataRegex);
                Matcher matcherbyteData = compilebyteData.matcher(group);
                while (matcherbyteData.find()) {
                    String byteData = matcherbyteData.group(1);//二进制流数据
                    Log.i(TAG, "二进制数据________________" + byteData);
                    //转换成图片
                    Bitmap bitmap = Base642Bitmap(byteData);
                    //mIamge.setImageBitmap(bitmap);
                    Drawable drawable = new BitmapDrawable(bitmap);
                   if (height>drawable.getIntrinsicHeight()){
                       //字体高度大于t图片高度
                       float h_offset = height / drawable.getIntrinsicHeight();
                       drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * h_offset+0.5), height);
                   }else {
                       drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                   }
                    MyImageSpan imageSpan = new MyImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
                    LogUtils.i(TAG, "字体高度 ： " + height + "  图片高度  ：" + drawable.getIntrinsicHeight());

                    spannableString.setSpan(imageSpan, startIndex, startIndex + endIndex, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);
                }
            }
            LogUtils.i(TAG,"最终的值  ：  "+spannableString.toString());
            textView.setText(spannableString);
        }


    }    /**
     * 截取字节流图片在textview显示
     *
     * @param textView  textview控件
     * @param strSource 数据源
     */
    public static void filterMTImage(MTextView textView, String strSource) {

        strSource = ToDBC(strSource);
        //测量textview的高度
        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.EXACTLY);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.EXACTLY);
        textView.measure(w, h);
        int height = textView.getMeasuredHeight();
        //  int width = textView.getMeasuredWidth();
        if (strSource != null) {
            Log.i(TAG, "所以得数据源++++++++++++++++" + strSource);
            //   String regex = "\\w+@\\w{2,6}(\\.\\w{2,3})+";
            String regex = "<img(\\s)src=\"(.){10,100}(\\.\\w{3})\">";//截取Url图片
            String imagRegex = "<(?i)img(\\s)src(.)*?>";//获取字节数据图片
            String byteDataRegex = ",((.)*?)\">";//过滤数据字节数据
            String replaceAllUrl = strSource.replaceAll(regex, "");//截取URl图片后
            Log.i(TAG, "截取URl后_____________________" + replaceAllUrl);
            Pattern compileImage = Pattern.compile(imagRegex, Pattern.CASE_INSENSITIVE);
            Matcher matcher = compileImage.matcher(replaceAllUrl);
            SpannableString spannableString = new SpannableString(replaceAllUrl);
            while (matcher.find()) {
                String group = matcher.group();
                Log.i(TAG, "获取二进制全数据+++++++++++++++++++" + group);
                //在原字符串中位置
                int startIndex = replaceAllUrl.indexOf(group);
                int endIndex = group.length();
                Pattern compilebyteData = Pattern.compile(byteDataRegex);
                Matcher matcherbyteData = compilebyteData.matcher(group);
                while (matcherbyteData.find()) {
                    String byteData = matcherbyteData.group(1);//二进制流数据
                    Log.i(TAG, "二进制数据________________" + byteData);
                    //转换成图片
                    Bitmap bitmap = Base642Bitmap(byteData);
                    //mIamge.setImageBitmap(bitmap);
                    Drawable drawable = new BitmapDrawable(bitmap);

                   if (height>drawable.getIntrinsicHeight()){
                       //字体高度大于t图片高度
                       float h_offset = height / drawable.getIntrinsicHeight();
                       drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * (h_offset+1)+0.5), height);

                   }else {
                       drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                   }
                    MyImageSpan imageSpan = new MyImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
                    LogUtils.i(TAG, "字体高度 ： " + height + "  图片高度  ：" + drawable.getIntrinsicHeight());
                    spannableString.setSpan(imageSpan, startIndex, startIndex + endIndex, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);
                }
            }
            LogUtils.i(TAG,"最终的值  ：  "+spannableString.toString());
            textView.setMText(spannableString);
        }


    } /**
     * 截取字节流图片在textview显示
     *
     * @param textView  textview控件
     * @param strSource 数据源
     */
    public static SpannableString filterImageSpanStr(TextView textView, String strSource) {
        //测量textview的高度
        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.EXACTLY);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.EXACTLY);
        textView.measure(w, h);
        int height = textView.getMeasuredHeight();
        //  int width = textView.getMeasuredWidth();
        if (strSource != null) {
            Log.i(TAG, "所以得数据源++++++++++++++++" + strSource);
            //   String regex = "\\w+@\\w{2,6}(\\.\\w{2,3})+";
            String regex = "<img(\\s)src=\"(.){10,100}(\\.\\w{3})\">";//截取Url图片
            String imagRegex = "<(?i)img(\\s)src(.)*?>";//获取字节数据图片
            String byteDataRegex = ",((.)*?)\">";//过滤数据字节数据
            String replaceAllUrl = strSource.replaceAll(regex, "");//截取URl图片后
            Log.i(TAG, "截取URl后_____________________" + replaceAllUrl);
            Pattern compileImage = Pattern.compile(imagRegex, Pattern.CASE_INSENSITIVE);
            Matcher matcher = compileImage.matcher(replaceAllUrl);
            SpannableString spannableString = new SpannableString(replaceAllUrl);
            while (matcher.find()) {
                String group = matcher.group();
                Log.i(TAG, "获取二进制全数据+++++++++++++++++++" + group);
                //在原字符串中位置
                int startIndex = replaceAllUrl.indexOf(group);
                int endIndex = group.length();
                Pattern compilebyteData = Pattern.compile(byteDataRegex);
                Matcher matcherbyteData = compilebyteData.matcher(group);
                while (matcherbyteData.find()) {
                    String byteData = matcherbyteData.group(1);//二进制流数据
                    Log.i(TAG, "二进制数据________________" + byteData);
                    //转换成图片
                    Bitmap bitmap = Base642Bitmap(byteData);
                    //mIamge.setImageBitmap(bitmap);
                    Drawable drawable = new BitmapDrawable(bitmap);

                   if (height>drawable.getIntrinsicHeight()){
                       //字体高度大于t图片高度
                       float h_offset = height / drawable.getIntrinsicHeight();
                       drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * h_offset+0.5), height);

                   }else {
                       drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                   }

                    MyImageSpan imageSpan = new MyImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
                    LogUtils.i(TAG, "字体高度 ： " + height + "  图片高度  ：" + drawable.getIntrinsicHeight());

                    spannableString.setSpan(imageSpan, startIndex, startIndex + endIndex, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);
                  //  spannableString.setSpan(imageSpan, 0, 50, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);
                }
            }

            //  textView.setText( Html.fromHtml(spannableString.toString().trim()));
            LogUtils.i(TAG,"最终的值  ：  "+spannableString.toString());
           // textView.setText(spannableString);
            return  spannableString;
        }
    return null;

    }


    /**
     * 将base64字节数组转换为bitmap
     */
    public static Bitmap Base642Bitmap(String base64) {
        // 将base64字节数组转换为普通的字节数组

        byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
        // 用BitmapFactory创建bitmap
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * 获取url
     *
     * @param sources
     * @return
     */
    public static List<String> filterUrl(String sources) {
        //    String regex="<(?i)img(\\s)src=\"((.)*?)\">";//截取Url图片
        String regex = "<img(\\s)src=\"((.){10,100}(\\.\\w{3}))\">";//截取Url图片
        Pattern compile = Pattern.compile(regex);
        List<String> list = new ArrayList<String>();
        if (sources != null) {
            Matcher matcher = compile.matcher(sources);

            while (matcher.find()) {
                String strUrl = matcher.group(2);
                Log.i(TAG, "全部的URl+++++++++" + strUrl);
                list.add(Config.IMAGE_URL + strUrl);
            }


        }


        return list;
    }

    /**
     * 判断是否显示标题图片
     * @param mQditem
     */
    public static boolean isShowIcon(ResTestProblemsInfo.TopicItemBean mQditem) {
        String itemBody = mQditem.getBody();//题目
        List<String> mTitlData = ImagFilterUtil.filterUrl(itemBody);
        for (int i = 0; i < mQditem.getOptions().size(); i++) {
            String answerValue = mQditem.getOptions().get(i).getValue();
            if (answerValue!=null){
                List<String> list = ImagFilterUtil.filterUrl(answerValue);
                if (list.size()>0){
                    for (String url : list) {
                        mTitlData.add(url);
                        LogUtils.i(TAG,"isshowIcon+++++++++++++++"+url);

                    }
                }

            }


        }

        if (mTitlData.size()>0){
            return true;
        }
        return false;
    }
    /**
     * 半角转换为全角
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }
}
